﻿using LPP.Core.Dtos;
using LPP.Entity.Orders;
using LPP.Entity.Work;
using LPP.EntityFrameworkCore;
using LPP.Service;
using LPP.Service.SmsService;
using LPP.Service.WorkerService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;

namespace LPP.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WorkersController : ControllerBase
    {
        private readonly SqlDbContext _context;
        private readonly IWorkerService _workerService;
        private readonly IImageUploadService _imageUploadService;
        private readonly SmsService _smsService;
        private readonly ILogger<WorkersController> _logger;

        public WorkersController(
            SqlDbContext context,
            IWorkerService workerService,
            IImageUploadService imageUploadService,
             SmsService smsService,
            ILogger<WorkersController> logger)
        {
            _context = context;
            _workerService = workerService;
            _imageUploadService = imageUploadService;
            _smsService = smsService;
            _logger = logger;
        }

        /// <summary>
        /// 手机号注册
        [HttpPost("RegisterWorker")]
        public async Task<IActionResult> RegisterWorker([FromBody] WorkerRegisterRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new { message = errors.FirstOrDefault() ?? "请求数据无效" });
                }
                if (request == null)
                {
                    return BadRequest(new { message = "请求数据不能为空" });
                }

                // 验证手机号格式
                if (string.IsNullOrEmpty(request.Phone) || !IsValidPhoneNumber(request.Phone))
                {
                    return BadRequest(new { message = "请输入正确的手机号" });
                }

                // 如果只传了手机号，发送验证码
                if (string.IsNullOrEmpty(request.VerifyCode))
                {
                    try
                    {
                        // 检查发送频率
                        if (await _smsService.IsSendingTooFrequentAsync(request.Phone))
                        {
                            return BadRequest(new { message = "发送太频繁，请稍后再试" });
                        }

                        var result = await _smsService.SendVerificationCodeAsync(request.Phone);
                        if (!result.Success)
                        {
                            return BadRequest(new { message = result.Message });
                        }
                        return Ok(new { message = result.Message });
                    }
                    catch (Exception ex) when (ex.Message.Contains("BUSINESS_LIMIT_CONTROL"))
                    {
                        return BadRequest(new { message = "发送请求过于频繁，请稍后再试" });
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "发送验证码失败");
                        return BadRequest(new { message = "发送验证码失败，请稍后重试" });
                    }
                }

                // 验证验证码
                var verifyResult = await _smsService.VerifyCodeAsync(request.Phone, request.VerifyCode);
                if (!verifyResult.Success)
                {
                    return BadRequest(new { message = verifyResult.Message });
                }

                // 检查手机号是否已注册
                var existingWorker = await _context.Workers.FirstOrDefaultAsync(w => w.Phone == request.Phone);
                if (existingWorker != null)
                {
                    return Ok(new
                    {
                        workerId = existingWorker.WorkerID,
                        message = existingWorker.Status == WorkerStatus.PendingVerification ?
                            "登录成功，请完善个人信息" : "登录成功",
                        needInfo = existingWorker.Status == WorkerStatus.PendingVerification
                    });
                }

                // 创建新工人记录
                var worker = new Worker
                {
                    Phone = request.Phone,
                    CreatedAt = DateTime.Now,
                    Status = WorkerStatus.PendingVerification
                };

                _context.Workers.Add(worker);
                await _context.SaveChangesAsync();
                return Ok(new
                {
                    workerId = worker.WorkerID,
                    message = "注册成功，请完善个人信息",
                    needInfo = true,
                    success = true  // 添加成功标志
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "注册工人时发生错误");
                return StatusCode(500, new { message = "注册失败，请稍后重试" });
            }
        }

        private bool IsValidPhoneNumber(string phone)
        {
            return !string.IsNullOrEmpty(phone) && System.Text.RegularExpressions.Regex.IsMatch(phone, @"^1[3-9]\d{9}$");
        }

        /// <summary>
        /// 上传身份证图片并更新工人信息
        /// </summary>
        [HttpPost("UploadIdCard")]
        public async Task<IActionResult> UploadIdCard(
     IFormFile idCardImage,
     [FromForm] string type,
     [FromForm] string workerId,
     [FromForm] string realName = null,
     [FromForm] string idCardNumber = null)
        {
            try
            {
                if (idCardImage == null || idCardImage.Length == 0)
                {
                    return BadRequest(new { message = "请上传图片" });
                }

                // 验证 workerId
                if (!int.TryParse(workerId, out int workerIdInt))
                {
                    return BadRequest(new { message = "无效的工人ID" });
                }

                // 上传图片到OSS
                var imageUrl = await _imageUploadService.UploadImageAsync(idCardImage, workerId, type);
                _logger.LogInformation("图片上传成功: {Url}", imageUrl);

                // 获取最新的工人信息
                var worker = await _context.Workers
                    .AsTracking()
                    .FirstOrDefaultAsync(w => w.WorkerID == workerIdInt);
                if (worker == null)
                {
                    return NotFound(new { message = "未找到工人信息" });
                }

                // 更新工人信息
                if (type.ToLower() == "front")
                {
                    worker.IdCardFront = imageUrl;
                    // 同时更新实名信息
                    if (!string.IsNullOrEmpty(realName) && !string.IsNullOrEmpty(idCardNumber))
                    {
                        worker.RealName = realName;
                        worker.IdCardNumber = idCardNumber;
                    }
                    _logger.LogInformation("更新正面照片: {Url}", imageUrl);
                }
                else if (type.ToLower() == "back")
                {
                    worker.IdCardBack = imageUrl;
                    _logger.LogInformation("更新背面照片: {Url}", imageUrl);
                }

                // 检查是否所有信息都已完整
                if (!string.IsNullOrEmpty(worker.IdCardFront) &&
                    !string.IsNullOrEmpty(worker.IdCardBack) &&
                    !string.IsNullOrEmpty(worker.RealName) &&
                    !string.IsNullOrEmpty(worker.IdCardNumber))
                {
                    worker.Status = WorkerStatus.Active;
                    worker.IsVerified = true;
                    _logger.LogInformation("工人认证完成");
                }
                // 标记需要更新的字段
                var entry = _context.Entry(worker);
                if (type.ToLower() == "front")
                {
                    entry.Property(x => x.IdCardFront).IsModified = true;
                    entry.Property(x => x.RealName).IsModified = true;
                    entry.Property(x => x.IdCardNumber).IsModified = true;
                }
                else
                {
                    entry.Property(x => x.IdCardBack).IsModified = true;
                }

                entry.Property(x => x.Status).IsModified = true;
                entry.Property(x => x.IsVerified).IsModified = true;

                // 立即保存更改
                await _context.SaveChangesAsync();
                _logger.LogInformation("保存了更改到数据库");

                return Ok(new
                {
                    imageUrl,
                    message = "上传成功",
                    status = worker.Status,
                    isVerified = worker.IsVerified
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传身份证图片时发生错误");
                return StatusCode(500, new { message = "上传失败，请稍后重试" });
            }
        }

        [HttpPost("CompleteWorkerInfo")]
        public async Task<IActionResult> CompleteWorkerInfo([FromBody] WorkerDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { message = "请检查提交的数据" });
                }

                var worker = await _context.Workers.FindAsync(request.WorkerId);
                if (worker == null)
                {
                    return NotFound(new { message = "未找到工人信息" });
                }

                // 更新所有相关字段
                worker.RealName = request.RealName;
                worker.IdCardNumber = request.IdCardNumber;
                worker.IdCardFront = request.IdCardFront;
                worker.IdCardBack = request.IdCardBack;
                worker.Status = WorkerStatus.Active;
                worker.IsVerified = true;
                worker.CreatedAt = DateTime.Now;

                await _context.SaveChangesAsync();

                return Ok(new
                {
                    message = "信息更新成功",
                    status = worker.Status,
                    isVerified = worker.IsVerified
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工人信息失败");
                return StatusCode(500, new { message = "保存失败，请稍后重试" });
            }
        }

        [HttpGet("{workerId}/income-statistics")]
        public async Task<IActionResult> GetIncomeStatistics(int workerId)
        {
            try
            {
                var worker = await _context.Workers
                    .Include(w => w.OrderDetails)
                    .ThenInclude(od => od.Order)
                    .FirstOrDefaultAsync(w => w.WorkerID == workerId);

                if (worker == null)
                {
                    return NotFound(new { message = "未找到工人信息" });
                }

                var now = DateTime.Now;
                var today = now.Date;
                var yesterday = today.AddDays(-1);
                var weekStart = today.AddDays(-(int)today.DayOfWeek);
                var monthStart = new DateTime(now.Year, now.Month, 1);
                var quarterStart = new DateTime(now.Year, ((now.Month - 1) / 3) * 3 + 1, 1);
                var yearStart = new DateTime(now.Year, 1, 1);

                var completedOrders = worker.OrderDetails
     .Where(od => (od.Order.Status == OrderStatus.Completed || od.Order.Status == OrderStatus.Reviewed) &&
                  od.Order.CompletedTime.HasValue)
     .ToList();

                // 计算收入
                foreach (var orderDetail in completedOrders)
                {
                    orderDetail.CalculateIncome();
                }

                var statistics = new WorkerIncomeStatisticsDto
                {
                    MonthlyIncome = completedOrders.Where(od => od.Order.CompletedTime >= monthStart).Sum(od => od.WorkerIncome),
                    YesterdayIncome = completedOrders.Where(od => od.Order.CompletedTime?.Date == yesterday).Sum(od => od.WorkerIncome),
                    WeeklyIncome = completedOrders.Where(od => od.Order.CompletedTime >= weekStart).Sum(od => od.WorkerIncome),
                    QuarterlyIncome = completedOrders.Where(od => od.Order.CompletedTime >= quarterStart).Sum(od => od.WorkerIncome),
                    YearlyIncome = completedOrders.Where(od => od.Order.CompletedTime >= yearStart).Sum(od => od.WorkerIncome),
                    TotalIncome = completedOrders.Sum(od => od.WorkerIncome),
                };

                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工人收入统计失败");
                return StatusCode(500, new { message = "获取统计信息失败" });
            }
        }

        [HttpGet("{workerId}/bills")]
        public async Task<IActionResult> GetBills(
            int workerId,
            [FromQuery] DateTime? startDate,
            [FromQuery] DateTime? endDate,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10)
        {
            try
            {
                var query = _context.OrderDetails
                    .Include(od => od.Order)
                    .Where(od => od.WorkerID == workerId);

                if (startDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime >= startDate);

                if (endDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime <= endDate);

                var total = await query.CountAsync();
                var bills = await query
                    .OrderByDescending(od => od.Order.CompletedTime)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .Select(od => new
                    {
                        od.OrderDetailID,
                        od.Order.OrderID,
                        od.Order.CompletedTime,
                        od.TotalPrice,
                        od.Order.Status,
                        od.ProductName,
                        od.Rating
                    })
                    .ToListAsync();

                return Ok(new
                {
                    total,
                    page,
                    pageSize,
                    bills
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工人账单明细失败");
                return StatusCode(500, new { message = "获取账单明细失败" });
            }
        }

        [HttpGet("platform/income-statistics")]
        public async Task<IActionResult> GetPlatformIncomeStatistics([FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate)
        {
            try
            {
                var query = _context.OrderDetails.AsQueryable();

                if (startDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime >= startDate);

                if (endDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime <= endDate);

                // 计算平台收入
                foreach (var orderDetail in query)
                {
                    orderDetail.CalculateIncome();
                }

                var statistics = new
                {
                    TotalIncome = await query.SumAsync(od => od.PlatformIncome),
                    OrderCount = await query.CountAsync(),
                    WorkerCount = await query.Select(od => od.WorkerID).Distinct().CountAsync()
                };

                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取平台收入统计失败");
                return StatusCode(500, new { message = "获取统计信息失败" });
            }
        }
    }
 }


   

